import MyModal from "@/components/MyModal"
import styles from './index.less'
import { useState } from "react"
import { Checkbox, Tag, message} from 'antd';
import EditFavoriteModal from "@/components/EditFavoriteModal";
import { useRequest } from "ahooks";
import { addFavorites, getFavoiteFolderArticles, getMyFavoitesFoldersList } from "@/services/favorite";
import { useParams } from "@umijs/max";
import { getUerInfo } from "@/utils/info";
type Props ={
    open:boolean,
    onClose:()=>void,
    onConfirm:(flag:boolean)=>void,
    id:string,
}

export default ({
    open,
    onClose,
    onConfirm,
}:Props) =>{
    const [v,setV] = useState({})
    const [editOpen,setEditOpen] = useState(false);
    const {id:articleId} = useParams();
    const {data,run,loading} = useRequest(getMyFavoitesFoldersList,{
        manual:!getUerInfo().id,
        onSuccess:(res)=>{
            getFlags(res)
        }
    })
    const getFlags = async(arr) =>{
       const result = await Promise.all((arr||[]).map(async(item) => {
        const res=  await getFavoiteFolderArticles(item.id)
        const flag = res?.find?.(i=>i.id===articleId)?.id
        return !!flag ? item.id : undefined
      }));
      const obj = result?.filter(Boolean).reduce((result,item)=>{
        result[item] = true;
        return result
      },{})
      setV({
        ...(v||{}),
        ...(obj||{})
      })
    }
    const {run:add} = useRequest(addFavorites,{
        manual:true,
        onSuccess:(res,[params])=>{
            onConfirm(params.ffId?.length)
        }
    })
    const onChange = (id) => {
        setV({
            ...(v||{}),
            [id]:!v[id]
        })
      };
    const onOk = () =>{
       const ffId = Object.entries(v).filter(([key,value])=>value).map(i=>i[0])
       add({
        articleId,
        ffId,
       })
    }
    
    return <MyModal  width={520}  title='选择收藏夹'open={open} close={onClose} onOk={onOk}  queryLoading={loading}>
        <div className={styles.checkList}>
            <a className={styles.item} onClick={()=>{setEditOpen(true)}}>+新建收藏夹</a>
            {
                data?.map?.((item,index)=>{
                    return <div key={index} className={styles.item} onClick={()=>{
                        onChange(item.id)
                    }}>
                        <Checkbox checked={v[item.id]} onChange={()=>onChange(item.id)}>
                        </Checkbox>
                        <div className={styles.title}>{item.name} <Tag color="blue" style={{ marginLeft: '12px' }}>
                        {item.permission === 1 ? '公开' : '私有'}
                    </Tag></div>
                        <div className={styles.number}>{item.total||0}</div>
                    </div>
                })
            }
        </div>
        <EditFavoriteModal open={editOpen} val={{}} close={()=>setEditOpen(false)} refresh={()=>{run()}}/>
    </MyModal>
}

